package cn.itsource.hrm.filter;

import cn.itsource.hrm.feignclients.RedisFeignClient;
import cn.itsource.hrm.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginCheckFilter extends ZuulFilter {

    @Autowired
    private RedisFeignClient redisFeignClient;
    @Override
    public String filterType() {
        return "pre";//前置Filter
    }

    //filter的执行顺序
    @Override
    public int filterOrder() {
        return 1;
    }

    //返回的Boolean值决定是否执行run方法，true表示要执行run方法
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        //判断资源路径，login，register不做登录检查,返回false
        if(StringUtils.hasLength(requestURI)&&(requestURI.endsWith("/login")||requestURI.endsWith("/register"))){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断是否有token
        if(!StringUtils.hasLength(token)){
            //不再继续执行，并且返回错误信息
            errorResponse();
            return null;
        }
        //从redis中获取登录信息
        AjaxResult ajaxResult = redisFeignClient.get(token);
        //获取不到token或者为空，不再继续执行，返回错误信息
        if(!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
            errorResponse();
        }
        return null;
    }

    private void errorResponse(){
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        //设置响应编码，json
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        //不再继续执行
        currentContext.setSendZuulResponse(false);

        // 2.返回错误信息 AjaxResult
        AjaxResult ajaxResult = AjaxResult.me().setSuccess(false).setMessage("登录错误");
        try {
            //响应错误信息
            response.getWriter().print(JSON.toJSONString(ajaxResult));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
